import { useState, useEffect } from 'react';
import axios from 'axios';
import './index.css';

function App() {
    const [messages, setMessages] = useState([]);
    const [input, setInput] = useState('');
    const [file, setFile] = useState(null);
    const [uploadProgress, setUploadProgress] = useState(0);
    const [fileName, setFileName] = useState('');
    const [showHistory, setShowHistory] = useState(false);
    const [historyConversations, setHistoryConversations] = useState([]);
    const [currentConversationId, setCurrentConversationId] = useState(null);
    const MAX_DISPLAY_LENGTH = 20;
    const [isLoggedIn, setIsLoggedIn] = useState(false);
    const [showLogin, setShowLogin] = useState(true);
    const [showRegister, setShowRegister] = useState(false);
    const [showForgotPassword, setShowForgotPassword] = useState(false);
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [message, setMessage] = useState(''); 
    const [selectedHistory, setSelectedHistory] = useState([]); 
    const [currentUsername, setCurrentUsername] = useState(''); 

    // 检查登录状态
    useEffect(() => {
        const checkLogin = async () => {
            try {
                const response = await axios.get('/api/check_login');
                if (response.data.isLoggedIn) {
                    // 严格清空所有相关状态
                    resetConversationState();
                    setIsLoggedIn(true);
                    setShowLogin(false);
                    setCurrentUsername(response.data.username);
                    // 重新获取历史记录
                    await fetchHistory();
                }
            } catch (error) {
                console.error('检查登录状态失败:', error);
            }
        };
        checkLogin();
    }, []);

    // 登录
    const handleLogin = async () => {
        try {
            const response = await axios.post('/api/login', { username, password });
            if (response.status === 200) {
                // 严格清空所有相关状态
                resetConversationState();
                setIsLoggedIn(true);
                setShowLogin(false);
                setMessage('登录成功'); 
                setCurrentUsername(response.data.username); 
                // 重新获取历史记录
                await fetchHistory();
            } else {
                setMessage(response.data.message); 
            }
        } catch (error) {
            setMessage(error.response?.data?.message || '登录失败，请稍后重试');
        }
    };

    // 重置对话相关状态
    const resetConversationState = () => {
        setMessages([]);
        setSelectedHistory([]);
        setCurrentConversationId(null);
        setInput('');
        setFile(null);
        setFileName('');
        setUploadProgress(0);
    };

    // 获取历史记录
    const fetchHistory = async () => {
        try {
            const historyResponse = await axios.get('/api/history');
            if (historyResponse.data && historyResponse.data.conversations) {
                setHistoryConversations(historyResponse.data.conversations);
            } else {
                console.error('历史记录响应数据格式错误:', historyResponse.data);
                setMessage('获取历史记录失败，数据格式错误');
            }
        } catch (error) {
            console.error('获取历史记录失败:', error);
            setMessage('获取历史记录失败，请稍后重试');
        }
    };
    
    // 注册
    const handleRegister = async () => {
        try {
            const response = await axios.post('/api/register', { username, password });
            if (response.status === 201) {
                setShowRegister(false);
                setShowLogin(true);
                setMessage('注册成功，请登录'); // 显示注册成功提示
            } else {
                setMessage(response.data.message); // 显示注册失败提示
            }
        } catch (error) {
            setMessage(error.response?.data?.message || '注册失败，请稍后重试');
        }
    };

    // 忘记密码
    const handleForgotPassword = async () => {
        try {
            const response = await axios.post('/api/forgot_password', { username });
            setMessage(response.data.message); // 显示忘记密码操作提示
            setShowForgotPassword(false);
            setShowLogin(true);
        } catch (error) {
            setMessage(error.response?.data?.message || '忘记密码请求失败，请稍后重试');
        }
    };

    // 注销
    const handleLogout = async () => {
        try {
            await axios.post('/api/logout');
            setIsLoggedIn(false);
            setShowLogin(true);
            setMessage('注销成功'); // 显示注销成功提示
        } catch (error) {
            setMessage(error.response?.data?.message || '注销失败，请稍后重试');
        }
    };

    // 新对话功能，覆盖原有历史对话
    const newConversation = async () => {
        if (messages.length > 0 && currentConversationId !== null) {
            try {
                const updateData = {
                    id: currentConversationId,
                    messages: [...messages]
                };
                // 调用更新接口覆盖原有对话
                await axios.put('/api/history', updateData);
                const response = await axios.get('/api/history');
                setHistoryConversations(response.data.conversations || []);
            } catch (error) {
                console.error('更新服务器端历史记录出错:', error);
            }
        }
        setMessages([]);
        setSelectedHistory([]);
        setCurrentConversationId(null); // 开启新对话，将 currentConversationId 置为 null
    };

    // 发送消息
    const sendMessage = async () => {
        if (!input.trim() && !file && !messages.some(msg => msg.role === 'file' && msg.fileContent)) return;

        const currentInput = input;
        const currentFile = file;
        const currentFileName = fileName;

        setInput('');
        setFile(null);
        setFileName('');

        const newMessages = [];
        let fileContent = null;
        if (currentFile) {
            try {
                fileContent = await readFileContent(currentFile);
                newMessages.push({
                    role: 'file',
                    content: currentFileName,
                    fileContent,
                    progress: 0
                });
            } catch (error) {
                console.error('读取文件内容失败:', error);
                newMessages.push({
                    role: 'file',
                    content: currentFileName,
                    fileContent: null,
                    progress: -1
                });
            }
        }
        if (currentInput.trim()) {
            // 聊天框中显示用户原始输入
            newMessages.push({
                role: 'user',
                content: currentInput
            });
        }

        setMessages(prev => [...prev, ...newMessages]);

        try {
            const formData = new FormData();
            let historyForAI = [];
            if (selectedHistory.length > 0) {
                // 只有选中历史对话时，才将全部历史记录传给 AI
                historyForAI = selectedHistory.map(msg => ({
                    role: msg.role === 'file' ? 'user' : msg.role === 'ai' ? 'assistant' : msg.role,
                    content: msg.role === 'file' ? `上传了文件: ${msg.content}` : msg.content.substring(0, 50)
                }));
                setSelectedHistory([]); // 清空选中的历史对话，后续对话不再传全部历史记录
            } else {
                // 后续对话只传最近的消息，这里假设只传最近 5 条消息
                const recentMessages = messages.slice(-5);
                historyForAI = recentMessages.map(msg => ({
                    role: msg.role === 'file' ? 'user' : msg.role === 'ai' ? 'assistant' : msg.role,
                    content: msg.role === 'file' ? `上传了文件: ${msg.content}` : msg.content.substring(0, 50)
                }));
            }

            formData.append('history', JSON.stringify(historyForAI));
            // 将带引导语的问题传给后端
            const guidedQuestion = currentInput;
            formData.append('query', guidedQuestion);

            const fileMessage = messages.find(msg => msg.role === 'file' && msg.fileContent);
            if (fileMessage) {
                const blob = new Blob([fileMessage.fileContent], { type: 'text/plain' });
                formData.append('file', blob, fileMessage.content);
            } else if (currentFile) {
                formData.append('file', currentFile);
            }

            const config = {
                headers: { 'Content-Type': 'multipart/form-data' },
                onUploadProgress: progressEvent => {
                    const percent = Math.round(
                        (progressEvent.loaded * 100) / progressEvent.total
                    );
                    setMessages(prev => prev.map(msg => 
                        msg.role === 'file' ? {...msg, progress: percent} : msg
                    ));
                }
            };

            const { data } = await axios.post('/api/chat', formData, config);

            const updatedMessages = [...messages, ...newMessages, { 
                role: 'assistant', 
                content: data.response
            }];
            setMessages(updatedMessages);

            try {
                const updateData = {
                    id: currentConversationId,
                    messages: updatedMessages
                };
                await axios.put('/api/history', updateData);
                const response = await axios.get('/api/history');
                setHistoryConversations(response.data.conversations || []);
            } catch (error) {
                console.error('更新服务器端历史记录出错:', error);
            }

        } catch (error) {
            console.error('Error:', error);
            setMessages(prev => prev.map(msg =>
                msg.role === 'file' ? {...msg, progress: -1} : msg
            ));
        } finally {
            setUploadProgress(0);
        }
    };

    // 读取文件内容
    const readFileContent = (file) => {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = (e) => resolve(e.target.result);
            reader.onerror = (error) => reject(error);
            reader.readAsText(file);
        });
    };

    // 文件上传处理
    const handleFile = (e) => {
        const selectedFile = e.target.files[0];
        if (selectedFile) {
            setFile(selectedFile);
            setFileName(selectedFile.name);
        }
    };

    // 加载历史对话
    const loadConversation = async (conversation) => {
        if (conversation && conversation.messages) {
            setMessages([...conversation.messages]);
            setCurrentConversationId(conversation.id);
            setSelectedHistory([...conversation.messages]); // 存储选中的历史对话
        } else {
            console.error('历史对话数据格式错误:', conversation);
        }
    };

    // 删除历史对话
    const deleteConversation = async (conversationId) => {
        // 弹出确认对话框
        const isConfirmed = window.confirm('确定要删除这条历史对话吗？');
        if (!isConfirmed) {
            return;
        }
        try {
            console.log('尝试删除对话，ID:', conversationId); 
            await axios.delete(`/api/history/${conversationId}`);
            const response = await axios.get('/api/history');
            setHistoryConversations(response.data.conversations || []);
            console.log('对话删除成功，更新历史记录');
        } catch (error) {
            console.error('删除服务器端历史记录出错:', error);
            setMessage('删除历史记录失败，请稍后重试');
        }
    };

    if (!isLoggedIn) {
        if (showLogin) {
            return (
                <div className="login-container">
                    <h2>登录</h2>
                    <input
                        type="text"
                        placeholder="用户名"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                    />
                    <input
                        type="password"
                        placeholder="密码"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                    />
                    <button onClick={handleLogin}>登录</button>
                    <p onClick={() => { setShowLogin(false); setShowRegister(true); }}>注册</p>
                    <p onClick={() => { setShowLogin(false); setShowForgotPassword(true); }}>忘记密码</p>
                    {message && <p style={{ color: 'red' }}>{message}</p>} {/* 显示提示信息 */}
                </div>
            );
        } else if (showRegister) {
            return (
                <div className="login-container">
                    <h2>注册</h2>
                    <input
                        type="text"
                        placeholder="用户名"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                    />
                    <input
                        type="password"
                        placeholder="密码"
                        value={password}
                        onChange={(e) => setPassword(e.target.value)}
                    />
                    <button onClick={handleRegister}>注册</button>
                    <p onClick={() => { setShowRegister(false); setShowLogin(true); }}>返回登录</p>
                    {message && <p style={{ color: 'red' }}>{message}</p>} {/* 显示提示信息 */}
                </div>
            );
        } else if (showForgotPassword) {
            return (
                <div className="login-container">
                    <h2>忘记密码</h2>
                    <input
                        type="text"
                        placeholder="用户名"
                        value={username}
                        onChange={(e) => setUsername(e.target.value)}
                    />
                    <button onClick={handleForgotPassword}>提交</button>
                    <p onClick={() => { setShowForgotPassword(false); setShowLogin(true); }}>返回登录</p>
                    {message && <p style={{ color: 'red' }}>{message}</p>} {/* 显示提示信息 */}
                </div>
            );
        }
    }

    return (
        <div className="app-container">
            {/* 显示当前登录的账号名称 */}
            {isLoggedIn && (
                <div style={{ position: 'fixed', top: '10px', right: '20px', zIndex: 1000 }}>
                    <p style={{ marginBottom: '5px' }}>当前用户: {currentUsername}</p>
                    <button onClick={handleLogout}>注销</button>
                </div>
            )}
            <div className="sidebar">
                <button className="new-conversation-btn" onClick={newConversation}>新对话</button>
                <button className="history-btn" onClick={() => setShowHistory(!showHistory)}>
                    {showHistory ? '隐藏历史对话' : '历史对话'}
                </button>
                {showHistory && (
                    <div className="history-list">
                        {historyConversations.length > 0 ? (
                            historyConversations.map((conversation) => {
                                const firstUserMessage = conversation.messages.find(
                                    (msg) => msg.role === 'user'
                                );
                                const displayText = firstUserMessage
                                    ? firstUserMessage.content.length > MAX_DISPLAY_LENGTH
                                        ? firstUserMessage.content.slice(0, MAX_DISPLAY_LENGTH) + '...'
                                        : firstUserMessage.content
                                    : '无用户消息';
                                return (
                                    <div key={conversation.id} className="history-item">
                                        <a
                                            href="#"
                                            onClick={(e) => {
                                                e.preventDefault();
                                                loadConversation(conversation);
                                            }}
                                        >
                                            {displayText}
                                        </a>
                                        <button
                                            className="delete-btn"
                                            onClick={(e) => {
                                                e.stopPropagation();
                                                deleteConversation(conversation.id); // 传递正确的 conversationId
                                            }}
                                        >
                                            删除
                                        </button>
                                    </div>
                                );
                            })
                        ) : (
                        <p>暂无历史对话</p>
                        )}
                    </div>
                )}
            </div>
            <div className="chat-container">
                <div className="messages">
                    {messages.map((msg, i) => (
                        <div key={`msg-${i}`} className={`message ${msg.role}`}>
                            {msg.role === 'file' ? (
                                <div className="file-message">
                                    <span>📁 {msg.content}</span>
                                    {msg.progress >= 0 ? (
                                        <div className="progress-container">
                                            <div className="progress-bar">
                                                <div
                                                    className="progress"
                                                    style={{ width: `${msg.progress}%` }}
                                                ></div>
                                            </div>
                                            <span>{msg.progress}%</span>
                                        </div>
                                    ) : (
                                        <span className="error">上传失败</span>
                                    )}
                                </div>
                            ) : msg.content}
                        </div>
                    ))}
                </div>

                <div className="input-area">
                    {/* 文件上传区域 */}
                    <div className="file-upload">
                        <label className="upload-button">
                            📁 上传文件
                            <input
                                type="file"
                                onChange={handleFile}
                                style={{ display: 'none' }}
                            />
                        </label>
                        {fileName && <span className="file-name">{fileName}</span>}
                    </div>

                    {/* 输入区域 */}
                    <div className="input-group">
                        <input
                            value={input}
                            onChange={(e) => setInput(e.target.value)}
                            onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
                            placeholder="输入消息..."
                        />
                        <button onClick={sendMessage}>发送</button>
                    </div>
                </div>
            </div>
        </div>
    );
}

export default App;